package yanyi.community.controller;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;

@Controller
@Slf4j
public class FileController {
    @ResponseBody
    @RequestMapping(value = "/file/upload")
    public Object upload(HttpServletRequest request, HttpServletResponse response, @RequestParam(value = "editormd" +
            "-image-file", required = false) MultipartFile multipartFile) {
        JSONObject jsonObject = new JSONObject();
        try {
            request.setCharacterEncoding("utf-8");
            response.setContentType("text/html");
          //  response.setHeader("Content-Type", "text/html");
            String rootPath = request.getSession().getServletContext().getRealPath("/resources/upload/");
            log.error("上传图片地址：" + rootPath);
            File filePath = new File(rootPath);
            if (!filePath.exists()) {
                filePath.mkdirs();
            }
            File realFile = new File(rootPath + File.separator + multipartFile.getOriginalFilename());
            FileUtils.copyInputStreamToFile(multipartFile.getInputStream(), realFile);
            jsonObject.put("success", 1);
            jsonObject.put("message", "上传成功");
            jsonObject.put("url", "/resources/upload/" + multipartFile.getOriginalFilename());

        } catch (Exception e) {
            log.error("上传异常:" + e.getMessage());
            jsonObject.put("success", 0);
            jsonObject.put("message", "上传失败");
            return jsonObject;
        }
        return jsonObject;
    }
}
